const webDataUtil = require('../../util/webDataUtil')
const reqlib = require('app-root-path').require
const btbAs = reqlib('/app/common/btb')
const commonDataCreate = require('./utils/commonDataCreate')
const AnalysisInfoFlag = reqlib('/app/analysis/analysisInfoFlag')
const BuySellMachine = reqlib('/app/analysis/buySellMachine')
const Performance = reqlib('/app/common/performance')

function parseValue (val) {
  return parseFloat(val || 0) || 0
}

const getWithKlineList = async (item) => {
  const key = item.code
  const klineResult = await Promise.all([
    webDataUtil.getFuturesKLinesAll({
      name: `${key}`,
      interval: '15m',
      count: 500
    }),
    webDataUtil.getFuturesKLinesAll({
      name: `${key}`,
      interval: '1h',
      count: 500
    }),
    webDataUtil.getFuturesKLinesAll({
      name: `${key}`,
      interval: '4h',
      count: 500
    }),
    webDataUtil.getFuturesKLinesAll({
      name: `${key}`,
      interval: '1d',
      count: 500
    })
  ])
  item.symbol = `${item.code}USDT`
  item.min_qty = item.f_min_qty
  item.max_qty = item.f_max_qty
  item.step_size = item.f_step_size
  item.min_notional = item.f_min_notional
  item.tick_size = item.f_tick_size
  item.klineList15m = klineResult[0]
  item.klineList1h = klineResult[1]
  item.klineList4h = klineResult[2]
  item.klineList1d = klineResult[3]
}

const analysisBtbItem = (item) => {
// 慢是因为分析2000天的，10个就20000天
  item.analysisInfoList15m = btbAs.getItemInfoList(item.klineList15m)
  item.analysisInfoList1h = btbAs.getItemInfoList(item.klineList1h)
  item.analysisInfoList4h = btbAs.getItemInfoList(item.klineList4h)
  item.analysisInfoList1d = btbAs.getItemInfoList(item.klineList1d)
  // 都转为从近到远
  item.analysisInfoList15m.reverse()
  item.analysisInfoList1h.reverse()
  item.analysisInfoList4h.reverse()
  item.analysisInfoList1d.reverse()
  item.analysisInfoList15m.forEach((v, index) => {
    commonDataCreate.asInfoExtend(item.analysisInfoList15m, v, index)
  })
  item.analysisInfoList1h.forEach((v, index) => {
    commonDataCreate.asInfoExtend(item.analysisInfoList1h, v, index)
  })
  item.analysisInfoList4h.forEach((v, index) => {
    commonDataCreate.asInfoExtend(item.analysisInfoList4h, v, index)
  })
  item.analysisInfoList1d.forEach((v, index) => {
    commonDataCreate.asInfoExtend(item.analysisInfoList1d, v, index)
  })
  item.klineList15m.reverse()
  item.klineList1h.reverse()
  item.klineList4h.reverse()
  item.klineList1d.reverse()
  item.analysisInfoFlag15m = new AnalysisInfoFlag({
    analysisInfoList: item.analysisInfoList15m,
    type: '15m',
    code: item.code
  })
  item.close = item.analysisInfoFlag15m.nowEmaInfo.close
  item.analysisInfoFlag1h = new AnalysisInfoFlag({
    analysisInfoList: item.analysisInfoList1h,
    type: '1h',
    code: item.code
  })
  item.analysisInfoFlag4h = new AnalysisInfoFlag({
    analysisInfoList: item.analysisInfoList4h,
    type: '4h',
    code: item.code
  })
  item.analysisInfoFlag1d = new AnalysisInfoFlag({
    analysisInfoList: item.analysisInfoList1d,
    type: '1d',
    code: item.code
  })
}

const getMarketBtbList = async (fsymbols) => {
  const futuresDailyRes = await webDataUtil.binance('getFuturesDaily')
  const futuresDailyData = futuresDailyRes.data || {}
  const list = []
  for (let key in futuresDailyData) {
    if (
      key.indexOf('USDT') !== -1 &&
      key.indexOf('USDT') !== 0 &&
      key.endsWith('USDT')
    ) {
      if (
        key.indexOf('DOWN') === -1 &&
        ['ETHUSDT', 'BTCUSDT'].indexOf(key) === -1
      ) {
        const itemData = futuresDailyData[key]
        const code = itemData.symbol.replace('USDT', '')
        itemData.code = code
        const fexInfo = btbAs.getEXInfo(fsymbols, code)
        if (fexInfo.status === 'TRADING') {
          list.push(itemData)
        }
      }
    }
  }
  return list
}

// 找币会找出10只，然后你交易基本上就只交易5只
module.exports = async function () {
  const p = new Performance()
  p.start()
  // 合约
  const fres = await webDataUtil.binance('getFuturesExchangeInfo')
  const fresData = fres.data || {}
  const fsymbols = fresData.symbols || []
  let marketBtbList = await getMarketBtbList(fsymbols)
  marketBtbList = marketBtbList.filter((item) => {
    const fexInfo = btbAs.getEXInfo(fsymbols, item.code)
    const minNotional = (parseValue(fexInfo.notional) || 0)
    if (
      (parseFloat(item.quoteVolume) / 50000000) > 0.1 &&
      minNotional <= 20
    ) {
      return true
    }
    return false
  })
  // 按信号和成交量排序
  marketBtbList.sort((a, b) => {
    const aq = parseFloat(a.quoteVolume)
    const bq = parseFloat(b.quoteVolume)
    return bq - aq
  })
  p.print('市场')
  const resultList = []
  for (let i = 0; i < marketBtbList.length; i++) {
    const item = marketBtbList[i]
    await getWithKlineList(item)
    analysisBtbItem(item)
    item.buySellMachine = new BuySellMachine({
      realBuySell: false,
      btbItem: item,
      futuresAccount: {},
      symbolAccount: {},
      marketInfo: false
    })
    const result = item.buySellMachine.findBtbByAnalysis()
    if (result) {
      resultList.push(item.code)
    }
    marketBtbList[i] = null
  }
  p.print('结束')
  return resultList
}
